package cn.wolfcode.p2p.controller;

import cn.wolfcode.p2p.base.annotation.IsLoginAnno;
import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.domain.RealAuth;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.CustomException;
import cn.wolfcode.p2p.base.service.IRealAuthService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.util.JSONResult;
import cn.wolfcode.p2p.util.UploadUtil;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class RealAuthController {

        @Value("${uploadpath}")
        private String basePath;
        @Autowired
        private IRealAuthService realAuthService;
        @Autowired
        private IUserInfoService userInfoService;
        @RequestMapping("realAuth")
        @IsLoginAnno
        private String realAuth(Model model){
                LoginInfo loginInfo = UserContext.getLoginInfo();
                UserInfo userInfo = userInfoService.getById(loginInfo.getId());

                if(userInfo.hasRealAuth()){
                        RealAuth realAuth = realAuthService.getById(userInfo.getRealAuthId());
                        model.addAttribute("realAuth",realAuth);
                        return "realAuth_result";
                }
                if(userInfo.getRealAuthId()!=null){
                        model.addAttribute("auditing",true);
                        return "realAuth_result";
                }
                return "realAuth";
        }

        @RequestMapping("realAuth_save")
        @ResponseBody
        public JSONResult realAuthSave(RealAuth realAuth){
                JSONResult jsonResult = new JSONResult();
                try {
                        realAuthService.apply(realAuth);
                }catch (CustomException e ){
                        jsonResult.setMsg(e.getMessage());//自定义的异常,避免所有异常都返回同样的信息给客户
                } catch (Exception e) {
                        e.printStackTrace();
                        jsonResult.setMsg("系统繁忙,请稍后再试");
                }
                return jsonResult;
        }



        @RequestMapping("uploadPhoto")
        @ResponseBody
        public String uploadPhoto(MultipartFile photo){
                return UploadUtil.upload(photo,basePath);
        }



}
